- Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathpalindrome checker 4 methods.py
85 lines (68 loc) · 2.15 KB
/
palindrome checker 4 methods.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 8 18:10:50 2018
@author: Administrator
"""
#check if a string is a palindrome
#reversing a string is extremely easy
#at first i was thinking about using pop function
#however, for an empty string, pop function is still functional
#it would not stop itself
#it would show errors of popping from empty list
#so i have to use the classic way, slicing
#each time we slice the final letter
#to remove the unnecessary marks, we have to use regular expression
importre
deff(n):
#this is the base case, when string is empty
#we just return empty
ifn=='':
returnn
else:
returnn[-1]+f(n[:-1])
defcheck(n):
#this part is the regular expression to get only characters
#and format all of em into lower cases
c1=re.findall('[a-zA-Z0-9]',n.lower())
c2=re.findall('[a-zA-Z0-9]',(f(n)).lower())
ifc1==c2:
returnTrue
else:
returnFalse
#alternatively, we can use deque
#we pop from both sides to see if they are equal
#if not return false
#note that the length of string could be an odd number
#we wanna make sure the pop should take action while length of deque is larger than 1
fromcollectionsimportdeque
defg(n):
c=re.findall('[a-zA-Z0-9]',n.lower())
de=deque(c)
whilelen(de) >=1:
ifde.pop()!=de.popleft():
returnFalse
returnTrue
#or we can use non recursive slicing
defh(n):
c=re.findall('[a-zA-Z0-9]',n.lower())
ifc[::-1]==c:
returnTrue
else:
returnFalse
#or creating a new list
#using loop to append new list from old list s popped item
defi(n):
c=re.findall('[a-zA-Z0-9]',n.lower())
d=[]
foriinrange(len(c)):
d.append(c.pop())
c=re.findall('[a-zA-Z0-9]',n.lower())
ifd==c:
returnTrue
else:
returnFalse
print(check('Evil is a deed as I live!'))
print(g('Evil is a deed as I live!'))
print(h('Evil is a deed as I live!'))
print(i('Evil is a deed as I live!'))
#for time and space complexity, python non recursive slicing wins